from sqlmodel import select
from sqlalchemy.orm import selectinload
from .dbconfig import get_session
from model.user_model import User,UserDB
from model.chat_model import ChatDB
from sqlalchemy.exc import IntegrityError
from datetime import datetime, timedelta
from user.email_send import verify_code
from fastapi import status, HTTPException

default_M = 0

# 数据库操作函数
async def get_user(username: str) -> User | None:
    """根据用户名获取用户"""
    session = next(get_session())#迭代器接收数据库会话
    try:
        # 使用 selectinload 预加载所有关联数据
        statement = select(User).where(User.username == username).options(
            selectinload(User.chats).selectinload(ChatDB.messages)
        )
        user = session.exec(statement).first()
        session.refresh(user)
        return user
    except Exception as e:
        print(f"获取用户出错: {str(e)}")
        return None
    finally:
        session.close()

async def get_user_by_id(user_id: int) -> User | None:
    """根据用户ID获取用户"""
    session = next(get_session())
    try:
        user = session.exec(select(User).where(User.id == user_id)).first()
        return session.refresh(user)
    except Exception as e:
        print(f"获取用户出错: {str(e)}")
        return None

async def create_user(user:UserDB) -> str | bool :
    """创建用户"""
    session = next(get_session())
    try:
        # 检查用户名是否存在
        username_exists = session.exec(select(User).where(User.username == user.username)).first()
        if username_exists:
            return "1"
        
        # 检查邮箱是否存在
        email_exists = session.exec(select(User).where(User.email == user.email)).first()
        if email_exists:
            return "2"
        
        # 创建新用户
        db_user = User(
            username=user.username,
            email=user.email,
            hashed_password=user.hashed_password,
            money=0
        )
        session.add(db_user)
        session.commit()
        return True
    except Exception as e:
        session.rollback()
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
    finally:
        session.close()